package com.hb.common.service.impl;

import com.hb.common.aspect.DbBackup;
import com.hb.common.aspect.DbRestore;
import com.hb.common.dto.Database;
import com.hb.common.dto.RestoreDto;
import com.hb.common.enums.DbEnum;
import com.hb.common.exception.DbBackupException;
import com.hb.common.factory.DbBackupFactory;
import com.hb.common.handler.backup.DbBackupHandler;
import com.hb.common.service.DatabaseService;
import com.hb.common.service.DbBackupService;
import com.hb.common.util.PathPermissions;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * 数据库备份与还原服务
 */
@Service
public class DbBackupServiceImpl implements DbBackupService {

    @Resource
    private PathPermissions pathPermissions;
    @Resource
    private DatabaseService databaseService;

    /**
     * 数据库备份
     *
     * @param id 数据库id
     */
    @DbBackup
    @Override
    public boolean backup(Integer id) throws DbBackupException {
        // 获取数据库信息
        Database database = databaseService.selectDecryptPasswordById(id).getData();
        if (database == null) {
            throw new DbBackupException("数据库不存在");
        }

        // 备份
        String dbType = database.getDbType().toUpperCase();
        DbBackupHandler backupHandler = DbBackupFactory.getHandler(Enum.valueOf(DbEnum.class, dbType));
        return backupHandler.backup(database);
    }

    /**
     * 数据库还原
     */
    @DbRestore
    @Override
    public boolean restore(RestoreDto restoreDto) throws DbBackupException {
        // 源数据库
        Database database = databaseService.selectDecryptPasswordById(restoreDto.getId()).getData();
        if (database == null) {
            throw new DbBackupException("源数据库不存在");
        }
        // 备份文件存放目录
        String dbFilePath = pathPermissions.getDbBackupPath(database) + restoreDto.getFileName();

        // 目标数据库
        Database targetDatabase = databaseService.selectDecryptPasswordById(restoreDto.getTargetId()).getData();
        if (targetDatabase == null) {
            throw new DbBackupException("目标数据库不存在");
        }

        // 还原
        String dbType = database.getDbType().toUpperCase();
        DbBackupHandler backupHandler = DbBackupFactory.getHandler(Enum.valueOf(DbEnum.class, dbType));
        return backupHandler.restore(targetDatabase, dbFilePath);
    }

}
